document.getElementById('addForm').addEventListener('submit', function(e) {
	e.preventDefault();
	let goodsId = document.getElementById("goodsId").value;
	let minPrice = document.getElementById("minPrice").value;
	let maxPrice = document.getElementById("maxPrice").value;
	let minPaintwear = document.getElementById("minPaintwear").value;
	let maxPaintwear = document.getElementById("maxPaintwear").value;
	// 创建一个对象存储商品信息
	let goods = {
		id: goodsId,
		minPrice: minPrice,
		maxPrice: maxPrice,
		minPaintwear: minPaintwear,
		maxPaintwear: maxPaintwear
	};
	// 将商品信息存储在Google插件中
	chrome.storage.sync.get("goodsList", function(result) {
		let goodsList = result.goodsList || [];
		goodsList.push(goods);
		chrome.storage.sync.set({
			"goodsList": goodsList
		}, function() {
			let newRow = document.createElement("tr");
			newRow.innerHTML = "<td>" + goodsId + "</td><td>" +
				minPrice + "-" + maxPrice + "</td><td>" +
				minPaintwear + "-" + maxPaintwear +
				"</td><td><button class='deleteButton'>删除</button></td>";
			// 添加成功后更新表格
			document.getElementById("goodsTable").appendChild(newRow);
			del();
		});
	});


});

function del() {
	// 给删除按钮添加点击事件
	let deleteButtons = document.getElementsByClassName("deleteButton")
	for (let i = 0; i < deleteButtons.length; i++) {
		deleteButtons[i].addEventListener("click", function(event) {
			// 获取当前点击的按钮所在的行元素
			let row = event.target.parentNode.parentNode;
			// 获取当前行的商品id
			let goodsId = row.getElementsByTagName("td")[0].innerHTML;
			// 从Google插件中删除对应商品
			chrome.storage.sync.get("goodsList", function(result) {
				let goodsList = result.goodsList || [];
				// 找到对应商品的索引
				let index = -1;
				for (let i = 0; i < goodsList.length; i++) {
					if (goodsList[i].id === goodsId) {
						index = i;
						break;
					}
				}
				// 删除商品并更新存储
				if (index !== -1) {
					goodsList.splice(index, 1);
					chrome.storage.sync.set({
						"goodsList": goodsList
					}, function() {
						// 删除行元素
						row.remove();
					});
				}
			});

		});
	}
};

// 从Google插件中获取商品列表
chrome.storage.sync.get("goodsList", function(result) {
	let goodsList = result.goodsList || [];

	// 遍历商品列表，创建表格行
	for (let i = 0; i < goodsList.length; i++) {
		let goods = goodsList[i];
		let newRow = document.createElement("tr");
		newRow.innerHTML = "<td>" + goods.id + "</td><td>" +
			goods.minPrice + "-" + goods.maxPrice + "</td><td>" +
			goods.minPaintwear + "-" + goods.maxPaintwear +
			"</td><td><button class='deleteButton'>删除</button></td>";
		document.getElementById("goodsTable").appendChild(newRow);
	}
	del();
});